﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<%@ Import Namespace="Apprenda.SaaSGrid" %>
<%@ Import Namespace="SaaSKit.Taskr.Service" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	Index.aspx
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="BodyContent" runat="server">

    <%

        bool canManageTasks = UserContext.Instance.IsAuthorized("Manage Tasks");

    %>

    <script type="text/javascript">

        function parseDate(date) {            
            d = new Date(parseInt(date.replace(')/', '').replace('/Date(', '')));
            return (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
        }

        function parseCreatedDate() {
            if (this.data.CreatedDate) {
                return parseDate(this.data.CreatedDate);
            } else {
                return "";
            }
        }

        function parseDueDate() {
            if (this.data.DueDate) {
                return parseDate(this.data.DueDate);
            } else {
                return "";
            }
        }

        // data will be the task task object being templated
        function parseAssignee(emptyText) {            
            if (this.data.Assignee) {
                if (this.data.Assignee.Id == '<%= UserContext.Instance.CurrentUser.Id %>') {
                    return "You";
                } else {
                    return this.data.Assignee.FirstName + " " + this.data.Assignee.LastName;
                }
            } else {
                return emptyText;
            }
        }

        // determines which view filter to use and then calls the appropriate
        // function in the Taskr library to retrieve a list of tasks
        function loadTasks() {            
            var type = $("input[name='viewSelector']:checked").val();            
            switch (type) {
                case 'user':
                    Taskr.listTasks(renderTasks, '<%= UserContext.Instance.CurrentUser.Id %>');                             
                    break;
                case 'all':
                    Taskr.listTasks(renderTasks);
                    break;
                default:
            }
        }

        // used as a callback for listing tasks, this 
        // fills the <div> container with the lists of tasks using the task template
        function renderTasks(tasks) {
            var taskList = $("#taskListContainer");
            var todoTmpl = $("#todoTmpl");
            var condensedTaskTmpl = $("#condensedTaskTmpl");                        
            taskList.empty();
            var type = $("input[name='viewSelector']:checked").val();
            switch (type) {
                case 'user':
                    todoTmpl.tmpl(tasks).appendTo(taskList);            
                    break;
                case 'all':
                    condensedTaskTmpl.tmpl(tasks).appendTo(taskList);
                    break;
                default:
            }

            postRender();

        }

        function renderActivity(activity, taskId) {
            var postList = $("#postedActivity-" + taskId);
            var postTmpl = $("#taskActivityTmpl");            
            postList.empty();          
            postTmpl.tmpl(activity).appendTo(postList);
        }

        // use this function to perform bindings, etc. that might
        // need to be done after items are added to the page view rendering.
        function postRender() {

            // add deletion trigger behavior to all delete links
            $("a.deleteTaskTrigger").click(deleteTask);

            // add completion trigger behavior to all completion links
            $("a.toggleCompletionTrigger").click(toggleCompletion);

            // add trigger to show task activity
            $("a.toggleActivityTrigger").click(toggleActivity);

        }

        // collects input from the new task form, and
        // attempts to add the task via a service call.
        function saveTask() {
            var task = {
                Summary: $("#newTaskSummary").val(),
                Description: $("#newTaskDescription").val(),
                DueDate: $("#newTaskDueDate").val(),
                Status: $("#newTaskStatus").val(),
                AssigneeId: $("#newTaskAssignee").val()
            }
            Taskr.addTask(task, addedHandler);
        }

        // callback for when a task is added
        function addedHandler() {
            $.fancybox.close();
            $("#taskList").empty();            
            loadTasks();
        }

        $(document).ready(function () {

            // turns the radio buttons contained within
            // the view selector into buttons via jqueryui
            $("#viewSelectContainer").buttonset();

            // attaches a behavior to the radio buttons so that when they are changed, 
            // the task list will reload based on the selection change
            $("input[name='viewSelector']").change(function () {
                loadTasks();
            });

            // turns the add task link into a trigger that will
            // open a fancybox modal to accept input from the user
            $("#addTaskTrigger").fancybox({
                transitionIn: 'elastic',
                transitionOut: 'elastic',
                title: 'Add a task. The only required field is the summary.'
            });

            // attaches a behavior to the save button on the new task form
            $("#addTaskSaveTrigger").click(function () {
                saveTask();
            });

            // attaches autocomplete behavior to the user search input box
            $("#newTaskAssignee").autocomplete({
                source: searchUsers,
                minLength: 3,
                focus: function (event, ui) {
                    $(event.target).val(ui.item.label);
                    return false;                
                },                
                select: function (event, ui) {
                    $(event.target).val(ui.item.label);
                    return false;                
                }
            });

            loadTasks();

        });

        // local handler for deleting a task, parses the 
        // id of the trigger causing the event.  The id will contain
        // the task id we are dealing with.
        function deleteTask(e) {            
            Taskr.removeTask(e.currentTarget.id.split("#", 2)[1], loadTasks);
        }

        // local handler for toggling the display of task activity, parses the 
        // id of the trigger causing the event.  The id will contain
        // the task id we are dealing with.
        function toggleActivity(e) {
            var taskId = e.currentTarget.id.split("#", 2)[1];            
            if ($("#postedActivity-" + taskId).is(':visible')) {
                $("#postedActivity-" + taskId).toggle();
            } else {
                $("#postedActivity-" + taskId).toggle();
                Taskr.listTaskActivity(renderActivity, taskId);
            }
        }

        // local handler for toggling task completion status, parses the 
        // id of the trigger causing the event.  The id will contain
        // the task id we are dealing with.
        function toggleCompletion(e) {            
            var obj = e.currentTarget.id.split("#", 3);
            if (obj.length > 2) {
                Taskr.toggleTaskCompletion(obj[1], obj[2], loadTasks);
            } else {
                Taskr.toggleTaskCompletion(loadTasks, obj[1], obj[2]);
            }
        }

        // calls the service method that searches API users (from the tenant), 
        // and return a collection of users whose first or last names begin with
        // the search term. (NOTE: this can be moved to the Taskr lib whenever).
        function searchUsers(request, response) {
        
            $.ajax({
                type: 'GET',
                url: '/Common/SearchUsers',
                data: { searchTerm: request.term },
                success: function (data) {                    
                    response($.map(data, function (item) {
                        return {
                            label: item.FirstName + " " + item.LastName,
                            value: item.Id
                        }
                    }));
                }
            });            

        } 
    
    </script>    
    
    <!-- The template for the FULL TO DO LIST display of a single task in a collection -->
    <script id="todoTmpl" type="text/html">
        
        <div class="task">
            <div class="task-top">
                <div class="actions left">
                    <a class="toggleCompletionTrigger toggleCompletionTrigger-{{if CompletedDate}}complete{{else}}open{{/if}}" id="deleteTask#{{= Id }}#{{if CompletedDate}}complete{{/if}}" />
                </div>
                <div class="main left">
                    <p class="summary"><a href="#">{{= Summary }}</a></p>
                    <p class="description">{{= Description }}</p>
                </div>
                <div class="actions right">

                    <% if(canManageTasks) { %>
                    
                        <a class="deleteTaskTrigger" id="deleteTask#{{= Id }}" />
                    
                    <% } %>
                    
                </div>
                <div class="metadata right">
                    {{if DueDate}}
                    <p class="duedate"><strong>${parseDueDate}</strong></p>
                    {{/if}}                    
                    {{if AssigneeId}}
                    <p class="assignee">${parseAssignee('Not Assigned')}</p>
                    {{/if}}
                    {{if Status}}
                    <p class="status">{{= Status }}</p>
                    {{/if}}
                </div>                
                <div class="clear-both"></div>
            </div>            
            <div class="task-bottom">            
                <div class="activitySwitch">        
                    <a class="toggleActivityTrigger" id="activityTrigger#{{= Id }}">Activity</a>
                </div>
                <div class="clear-both"></div>
                <div class="postedActivity" id="postedActivity-{{= Id }}" style="display: none;">
                </div>                            
            </div>
        </div>

    </script>
    <!-- end template -->

    <!-- The template for the CONDENSED display of a single task in a collection -->
    <script id="condensedTaskTmpl" type="text/html">
        
        <div class="task">
            <div class="task-top-condensed">
                <div class="actions left">
                    <a class="toggleCompletionTrigger toggleCompletionTrigger-{{if CompletedDate}}complete{{else}}open{{/if}}" id="deleteTask#{{= Id }}#{{if CompletedDate}}complete{{/if}}" />
                </div>
                <div class="main left">
                    <p class="summary"><a href="#">{{= Summary }}</a></p>
                </div>
                <div class="actions right">
                    
                    <% if(canManageTasks) { %>
                    
                        <a class="deleteTaskTrigger" id="deleteTask#{{= Id }}" />
                    
                    <% } %>

                </div>
                <div class="metadata right">
                    {{if AssigneeId}}
                    <span class="assignee">${ parseAssignee('Not Assigned') }</span>
                    {{/if}}
                    {{if DueDate}}
                    <span class="duedate">${parseDueDate}</span>
                    {{/if}}
                    {{if Status}}
                    <span class="status">{{= Status }}</span>
                    {{/if}}
                </div>                
                <div class="clear-both"></div>
            </div>            
            <div class="condensed-task-bottom">            
            </div>
        </div>

    </script>
    <!-- end template -->

    <script id="taskActivityTmpl" type="text/html">        
        <div class="activityPost">
            <p class="summary">
                <strong>${parseCreatedDate} by {{= Author }}</strong>
            </p>
            <p class="description">
                {{= Description }}
            </p>        
        </div>
    </script>

	<div class="content-block">
	    
        <div class="content-block-header">
		    <div class="content-block-header-left"></div>
			    <h3>Tasks</h3>
                <div id="viewSelectContainer" class="viewSelector">	
		            <input type="radio" id="myTasks" name="viewSelector" value="user" checked="checked" />
                    <label for="myTasks">Your To Do List</label>

                    <% if(canManageTasks) { %>
		            
                    <input type="radio" id="allTasks" name="viewSelector" value="all" />
                    <label for="allTasks">Everyone's Tasks</label>			

                    <% } %>

                </div>                                                          
			<div class="content-block-header-right"></div>
			<div class="clear-both"></div>
		</div>

        <div class="block-panel">                   
            <div id="taskListContainer"></div>            
            <div class="clear-both"></div>
        </div>

		<div class="content-block-footer">            
		    <div class="content-block-footer-left"></div>
			<div class="content-block-footer-right"></div>
			<div class="clear-both"></div>
		</div>

    </div>    

    <div style="display: none;">
        <div id="taskForm" class="standard-form">
            
            <div class="standard-form-left">
			    <div class="field">
				        <label for="newTaskSummary">Summary</label>                    
                        <%= Html.TextBox("newTaskSummary", "", new { Id = "newTaskSummary", Class = "textbox" })%>					    
				</div>

			    <div class="field">
				        <label for="newTaskDescription">Notes</label>                   
                        <%= Html.TextArea("newTaskDescription", "", new { Id = "newTaskDescription", Class = "textarea" })%>					    
				</div>
            </div>

            <div class="standard-form-right">

			    <div class="field">
				        <label for="newTaskDueDate">Due Date</label>                   
                        <%= Html.TextBox("newTaskDueDate", "", new { Id = "newTaskDueDate", Class = "textbox" })%>
				</div>

                <% var maxDate = SubscriptionContext.Instance.GetBound("boundary_DueDateDaysFromToday").Value; %>
                        
                <script type="text/javascript">

                    $(function () {
                        $('#newTaskDueDate').datepicker({maxDate: '+' + <%= maxDate %> + 'd'});
                    });
                        
                </script>

                <div class="field" style="display: <%= canManageTasks ? "block" : "none" %>">
				        <label for="newTaskAssignee">Assignee</label>                   
                        <%= Html.TextBox("newTaskAssignee", "", new { Id = "newTaskAssignee", Class = "textbox" })%>
				</div>

                <%                    
                    if (((SettingsDTO)ViewData["CustomTaskrSettings"]).CustomStatuses != null)
                    {

                        var statuses = ((SettingsDTO)ViewData["CustomTaskrSettings"]).CustomStatuses.Split(',');
                        System.Collections.Generic.List<SelectListItem> items = new System.Collections.Generic.List<SelectListItem>();
                        items.Add(new SelectListItem());
                        foreach (string status in statuses)
                        {
                            items.Add(new SelectListItem() { Text = status });
                        }
                %>

			    <div class="field">
				        <label for="newTaskStatus">Status</label>
                        <%= Html.DropDownList("newTaskStatus", items)%>
				</div>

                <% } %>
            
            </div>

            <div class="clear-both"></div>

            <button id="addTaskSaveTrigger">Add Task</button>                

        </div>
    </div>

</asp:Content>

<asp:Content runat="server" ContentPlaceHolderID="SidebarContent">

    <div class="left-block">
        <a id="addTaskTrigger" href="#taskForm">Add a Task</a>
    </div>

</asp:Content>
